#include <termExecute.h>
#include <hexstr.h>

void termPrintOut(const char *format, ...)
{
    // for c51
    static DEV_C51_XDATA_FLAG char tmpout[128];
    int tmpsize = 0;
    va_list vArgList;
    if (format == NULL)
    {
        printf("# ");
        return;
    }
    va_start(vArgList, format);
    // if device is 51, have to use vsprintf. cannot ensure over write!
    // if device use c99, we can use vsnprintf.
    tmpsize = vsprintf(tmpout, format, vArgList);
    va_end(vArgList);
    tmpout[tmpsize] = 0;
    printf("%s", tmpout);
    printf("\n");
}

typedef struct
{
    const char *cmdName;
    const char *cmdExplain;
} termCmdInfoStc;

static DEV_C51_CODE_FLAG termCmdInfoStc termCmdList[] = {
    {"help", "show cmd list"},
    {"ls", "check ls cmd"},
    {"ps", "ps cmd"},
    {"exit", "exit code"},
};
// if not use 51, function can use callback function into termCmdList
void termCmd_help(char *cmdPtr)
{
    int i;
    termPrintOut("term cmd list:");
    for (i = 0; i < (int)ARRAY_LEN(termCmdList); i++)
    {
        termPrintOut("%-10s:%s", termCmdList[i].cmdName, termCmdList[i].cmdExplain);
    }
}
void termCmd_ls(char *cmdPtr)
{
    char *tmpdtPtr;
    uint8_t tmpid = 1;
    do
    {
        tmpdtPtr = strtok(NULL, " ");
        if (!tmpdtPtr)
        {
            break;
        }
        termPrintOut("in parm%d:%s", tmpid++, tmpdtPtr);
    } while (1);
    if (tmpid == 1)
    {
        termPrintOut("has no parm");
    }
}
void termCmd_ps(char *cmdPtr)
{
    system("ps");
}
void termCmd_exit(char *cmdPtr)
{
    termPrintOut("do exit");
    exit(1);
}

int termExeUpdate(char *exeStr)
{
    // logdebugc("%s", getHexStr(exeStr, strlen(exeStr)).str);
    char *tmpptr = strtok(exeStr, " ");
    if (tmpptr && strlen(tmpptr) > 1 && tmpptr[strlen(tmpptr) - 1] == '\n')
    {
        tmpptr[strlen(tmpptr) - 1] = '\0';
    }
    if (tmpptr == NULL || tmpptr[0] == '\n')
    {
    }
    else if (strcmp(tmpptr, "help") == 0) 
    {                                     
        termCmd_help(tmpptr);          
    }
    else if (strcmp(tmpptr, "ls") == 0) 
    {                                     
        termCmd_ls(tmpptr);          
    }
    else if (strcmp(tmpptr, "ps") == 0) 
    {                                     
        termCmd_ps(tmpptr);          
    }
    else if (strcmp(tmpptr, "exit") == 0) 
    {                                     
        termCmd_exit(tmpptr);          
    }
    else
    {
        // logdebugc("%s", getHexStr(tmpptr, strlen(tmpptr)).str);
        termPrintOut("unknown cmd!:%s", tmpptr);
        termPrintOut("help show cmd list");
    }
    termPrintOut(NULL);
    return 1;
}